<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 头部区域 -->
    <div class="bg-white shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <h1 class="text-2xl font-bold text-gray-800">
          标签管理
        </h1>
        <p class="text-gray-600 mt-1">
          管理系统标签，支持模糊查询和滚动加载
        </p>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="container mx-auto px-4 py-6">
      <div class="bg-white rounded-lg shadow-sm p-4">
        <div class="flex flex-col sm:flex-row gap-4">
          <UInput
            v-model="searchKeyword"
            placeholder="请输入标签名称进行搜索..."
            class="flex-1"
            @keyup.enter="handleSearch"
          >
            <template #leading>
              <UIcon
                name="i-heroicons-magnifying-glass"
                class="w-5 h-5"
              />
            </template>
          </UInput>
          <UButton
            color="primary"
            variant="solid"
            size="sm"
            @click="handleSearch"
          >
            搜索
          </UButton>
          <UButton
            color="neutral"
            variant="outline"
            size="sm"
            @click="resetSearch"
          >
            重置
          </UButton>
        </div>
      </div>
    </div>

    <!-- 标签列表区域 -->
    <div class="container mx-auto px-4 pb-20">
      <div
        v-if="loading && tags.length === 0"
        class="flex justify-center items-center h-64"
      >
        <UILoadingSpinner class="w-8 h-8 text-primary" />
      </div>

      <div
        v-else-if="tags.length === 0"
        class="bg-white rounded-lg shadow-sm p-8 text-center"
      >
        <UIcon
          name="i-heroicons-tag"
          class="w-16 h-16 text-gray-400 mx-auto mb-4"
        />
        <p class="text-gray-500 text-lg">
          暂无标签数据
        </p>
        <p class="text-gray-400 mt-2">
          点击右下角按钮创建第一个标签
        </p>
      </div>

      <div
        v-else
        class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
      >
        <div
          v-for="tag in tags"
          :key="tag.id"
          class="bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow duration-200 overflow-hidden"
        >
          <div class="p-6">
            <div class="flex items-start justify-between mb-4">
              <h3 class="text-lg font-semibold text-gray-800 truncate">
                {{ tag.name }}
              </h3>
              <div class="flex space-x-2">
                <UButton
                  color="primary"
                  variant="ghost"
                  size="sm"
                  :to="`/system/tag-edit/${tag.id}`"
                >
                  <UIcon
                    name="i-heroicons-pencil"
                    class="w-4 h-4"
                  />
                </UButton>
                <UButton
                  color="error"
                  variant="ghost"
                  size="sm"
                  @click="confirmDelete(tag)"
                >
                  <UIcon
                    name="i-heroicons-trash"
                    class="w-4 h-4"
                  />
                </UButton>
              </div>
            </div>

            <div class="space-y-2">
              <div class="flex items-center text-sm text-gray-600">
                <UIcon
                  name="i-heroicons-arrows-up-down"
                  class="w-4 h-4 mr-2"
                />
                <span>排序：{{ tag.sortOrder || 0 }}</span>
              </div>

              <div
                v-if="tag.remark"
                class="flex items-start text-sm text-gray-600"
              >
                <UIcon
                  name="i-heroicons-document-text"
                  class="w-4 h-4 mr-2 mt-0.5 flex-shrink-0"
                />
                <span class="break-words">{{ tag.remark }}</span>
              </div>

              <div class="flex items-center text-xs text-gray-400 pt-2">
                <UIcon
                  name="i-heroicons-clock"
                  class="w-3 h-3 mr-1"
                />
                <span>{{ formatDate(tag.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div
        v-if="hasMore && !loading"
        class="flex justify-center mt-8"
      >
        <UButton
          color="primary"
          variant="outline"
          :loading="loadingMore"
          @click="loadMore"
        >
          加载更多
        </UButton>
      </div>

      <div
        v-if="loadingMore"
        class="flex justify-center mt-8"
      >
        <UILoadingSpinner class="w-6 h-6 text-primary" />
      </div>

      <div
        v-if="!hasMore && tags.length > 0"
        class="text-center mt-8 text-gray-500"
      >
        没有更多数据了
      </div>
    </div>

    <!-- 悬浮新增按钮 -->
    <UButton
      icon="i-heroicons-plus"
      color="primary"
      variant="solid"
      size="lg"
      class="fixed bottom-6 right-6 rounded-full w-14 h-14 shadow-lg hover:shadow-xl transition-all duration-300 z-10 flex items-center justify-center"
      to="/system/tag-create"
    />

    <!-- 删除确认模态框 -->
    <UModal
      v-model="showDeleteModal"
      title="确认删除"
    >
      <div class="p-6">
        <p class="text-gray-700 mb-6">
          确定要删除标签 <span class="font-semibold text-red-600">{{ tagToDelete?.name }}</span> 吗？此操作不可恢复。
        </p>

        <div class="flex justify-end space-x-3">
          <UButton
            color="neutral"
            variant="outline"
            :disabled="deleting"
            @click="showDeleteModal = false"
          >
            取消
          </UButton>
          <UButton
            color="error"
            variant="solid"
            :loading="deleting"
            @click="deleteTag"
          >
            删除
          </UButton>
        </div>
      </div>
    </UModal>
  </div>
</template>

<script setup lang="ts">
import type { Tag } from '~/types/tag'

// 页面元数据
definePageMeta({
  layout: 'default',
  title: '标签管理'
})

// 响应式数据
const searchKeyword = ref('')
const tags = ref<Tag[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const deleting = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(12)

// 模态框状态
const showDeleteModal = ref(false)
const tagToDelete = ref<Tag | null>(null)

// 初始化
onMounted(() => {
  fetchTags()
})

// 获取标签列表
const fetchTags = async (reset = false) => {
  if (reset) {
    currentPage.value = 1
    tags.value = []
    hasMore.value = true
  }

  if (loading.value || !hasMore.value) return

  loading.value = true

  try {
    const params = new URLSearchParams({
      page: currentPage.value.toString(),
      limit: pageSize.value.toString()
    })

    if (searchKeyword.value) {
      params.append('search', searchKeyword.value)
    }

    const response = await $fetch(`/api/tag/tags?${params.toString()}`)

    if (response.success) {
      const newTags = response.data

      if (reset) {
        tags.value = newTags
      } else {
        tags.value = [...tags.value, ...newTags]
      }

      hasMore.value = currentPage.value < response.pagination.totalPages
    } else {
      useToast().add({
        title: '获取标签列表失败',
        description: response.message || '请稍后重试',
        color: 'error'
      })
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    useToast().add({
      title: '获取标签列表失败',
      description: '网络错误，请稍后重试',
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (loadingMore.value || !hasMore.value) return

  loadingMore.value = true
  currentPage.value++

  try {
    const params = new URLSearchParams({
      page: currentPage.value.toString(),
      limit: pageSize.value.toString()
    })

    if (searchKeyword.value) {
      params.append('search', searchKeyword.value)
    }

    const response = await $fetch(`/api/tag/tags?${params.toString()}`)

    if (response.success) {
      const newTags = response.data
      tags.value = [...tags.value, ...newTags]
      hasMore.value = currentPage.value < response.pagination.totalPages
    } else {
      useToast().add({
        title: '加载更多失败',
        description: response.message || '请稍后重试',
        color: 'error'
      })
    }
  } catch (error) {
    console.error('加载更多失败:', error)
    useToast().add({
      title: '加载更多失败',
      description: '网络错误，请稍后重试',
      color: 'error'
    })
  } finally {
    loadingMore.value = false
  }
}

// 搜索
const handleSearch = () => {
  fetchTags(true)
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  fetchTags(true)
}

// 确认删除
const confirmDelete = (tag: Tag) => {
  tagToDelete.value = tag
  showDeleteModal.value = true
}

// 删除标签
const deleteTag = async () => {
  if (!tagToDelete.value) return

  deleting.value = true

  try {
    const response = await $fetch(`/api/tag/tags/${tagToDelete.value.id}`, {
      method: 'DELETE'
    })

    if (response.success) {
      tags.value = tags.value.filter(tag => tag.id !== tagToDelete.value?.id)
      showDeleteModal.value = false
      tagToDelete.value = null

      useToast().add({
        title: '删除成功',
        description: '标签已成功删除',
        color: 'success'
      })
    } else {
      useToast().add({
        title: '删除失败',
        description: response.message || '请稍后重试',
        color: 'error'
      })
    }
  } catch (error) {
    console.error('删除标签失败:', error)
    useToast().add({
      title: '删除失败',
      description: '网络错误，请稍后重试',
      color: 'error'
    })
  } finally {
    deleting.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>
